package com.bbzn.device.client.utils;

import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Pattern;

public class BeanVOUtils {
    //判断所填的对象列表中是否有空值
    public static boolean anyNotNull(final Object... values) {
        return firstNonNull(values);
    }
    public static <T> boolean firstNonNull(final T... values) {
        if (values == null) {
            return false;
        }
        for (final T val : values) {
            if (val == null || val == "" ) {
                return false;
            }
        }
        return true;
    }

    /**
     * 将对象转换成map集合 key为字段名 value为字段值
     * @param obj
     * @return
     * @throws Exception
     */
    public static Map<String, String> objectToMap(Object obj) throws Exception {
        if(obj == null){
            return null;
        }
        Map<String, String> map = new HashMap<>();
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            if(StringUtils.isEmpty(field.getName()) || null==field.get(obj)){
                continue;
            }
            if(field.getName().equals("serialVersionUID")){
                continue;
            }
            map.put(field.getName(), field.get(obj).toString());
        }
        return map;
    }


    /**
     * 数组顺序颠倒
     */
    public String[] swapOrder(String[] arr){
        int length = arr.length;
        for(int i=0;i<length/2;i++){
            String temp = arr[i];
            arr[i] = arr[length-1-i];
            arr[length-1-i] = temp;
        }
        return arr;
    }

    /**
     * 判断是否为数字
     * @param str
     * @return
     */
    public boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     * 去重的方法
     * @param <T>
     * @param keyExtractor
     * @return
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }

}
